package com.newtouch.xcd.cms.job.handler;

import cn.hutool.json.JSONUtil;
import com.newtouch.xcd.cms.config.FeignCrmConfig;
import com.newtouch.xcd.cms.service.TrustService;
import com.newtouch.xcd.cms.service.impl.FeignCrmService;
import com.newtouch.xcd.cms.to.crm.CrmData;
import com.newtouch.xcd.common.constants.RedisKeyDict;
import com.newtouch.xcd.common.constants.ResponseCode;
import com.newtouch.xcd.common.to.CommonResult;
import com.newtouch.xcd.mft.vo.CrmQueryDetailsOfFamilyTrustTransactionsReq;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MyFamilyTrustTradeDetailJobHandler extends IJobHandler {

    @Autowired
    private TrustService trustService;

    @Autowired
    private FeignCrmService feignCrmService;

    @Autowired
    private FeignCrmConfig feignCrmConfig;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @XxlJob(value = "MyFamilyTrustTradeDetailJobHandler")
    @Override
    public ReturnT<String> execute(String s) throws Exception {

        Boolean successFlag = true;

        //每天0点，加载所有的我的家族信托对应的交易记录，然后压入缓存。
        //要用多线程来做。

        List<String> xtNumberList = this.trustService.queryXtNumberList();

        String token = this.feignCrmConfig.getToken();

        for (String xtNumber : xtNumberList) {

            try {
                String key = RedisKeyDict.CrmCache.MY_FAMILY_TRUST_TRADE_DETAIL.getCode() + xtNumber;

                CrmQueryDetailsOfFamilyTrustTransactionsReq req = new CrmQueryDetailsOfFamilyTrustTransactionsReq(xtNumber);

                CommonResult<CrmData> result = this.feignCrmService.queryDetailsOfFamilyTrustTransactions(req, token, "Customer", "getCustomerTrustInfo");

                String responseCode = result.getCode();
                String message = result.getMessage();

                if (ResponseCode.R200.getCode().equals(responseCode)) {
                    CrmData crmData = result.getData();
                    this.stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonPrettyStr(crmData));
                } else {
                    successFlag = false;
                    XxlJobLogger.log("信托编号:{},加载数据异常。错误码:{},错误信息:{}", xtNumber, responseCode, message);
                }

            } catch (Exception e) {
                successFlag = false;
                XxlJobLogger.log("信托编号:{},加载数据异常。", xtNumber);
            }

        }

        if (successFlag) {
            return ReturnT.SUCCESS;
        } else {
            return ReturnT.FAIL;
        }
    }
}
